package com.shengwei.truck.driver.view.ui.map;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.shengwei.truck.driver.view.ui.app.MyApplication;
import com.shengwei.truck.driver.R;
import com.shengwei.truck.driver.bean.Result;
import com.shengwei.truck.driver.bean.task.JsonTaskDetailData;
import com.shengwei.truck.driver.databinding.FragmentMapBinding;
import com.shengwei.truck.driver.permission.MyLocationRequestPermission;
import com.shengwei.truck.driver.permission.RxjavaPermissionUtil;
import com.shengwei.truck.driver.utils.MyLogCat;
import com.shengwei.truck.driver.utils.SPUtils;
import com.shengwei.truck.driver.view.ui.BaseFragment;
import com.shengwei.truck.driver.view.ui.MainActivity;
import com.shengwei.truck.driver.vm.TaskDetailViewModel;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import io.reactivex.functions.Consumer;

import static android.content.Context.SENSOR_SERVICE;

/**
 * 展示定位图层3种定位模式
 */
public class MapFragment extends BaseFragment<TaskDetailViewModel, FragmentMapBinding> implements MyLocationRequestPermission,SensorEventListener, View.OnClickListener {
    // 定位相关
    private ProgressDialog locProgressDialog;
    private static final int STATE_IDLE = 0; //定位状态，空闲，没有开启定位。
    private final int STATE_REQUEST_LOC_FOR_CLICK = 1; //定位状态：请求定位“我的位置”（点击了“我的位置”按钮）
    private int curLocState = STATE_IDLE;
    // 定位图层显示方式
    private MyLocationConfiguration.LocationMode mCurrentMode;
    private MyLocationData myLocationData;
    private SensorManager mSensorManager;
    private Double lastX = 0.0;
    private int mCurrentDirection = 0; //当前放向，从正北顺时针开始0-360
    private double mCurrentLat = 0.0; //当前纬度
    private double mCurrentLon = 0.0; //当前经度
    private float mCurrentAccracy; //精度半径，米

    // 初始化地图
    private BaiduMap mBaiduMap;
    public String TAG = "MapFragment";
    //当前任务
    private String mCurTaskId;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        MyLogCat.i(TAG,"onCreate");
        super.onCreate(savedInstanceState);
    }

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        MyLogCat.i(TAG,"onCreateView");
        View root = super.onCreateView(inflater,container,savedInstanceState);
        
        initView();
        // 获取传感器管理服务
        mSensorManager = (SensorManager) getActivity().getSystemService(SENSOR_SERVICE);
        // 为系统的方向传感器注册监听器
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_UI);
        //定位图层
        initMyLocationLayer();
        EventBus.getDefault().register(this);
        //监听接口返回的数据
        initLiveDataObersve();

        return root;
    }

    private void initView() {
        mDataBinding.imgBtMyLoc.setOnClickListener(this);
        mDataBinding.imgBtTrack.setOnClickListener(this);

        //拨打电话
        mDataBinding.loadUnloadAddress.imvPublishPhone.setOnClickListener(this);
        mDataBinding.loadUnloadAddress.tvPublishPhone.setOnClickListener(this);
        mDataBinding.loadUnloadAddress.imvRecvPhone.setOnClickListener(this);
        mDataBinding.loadUnloadAddress.tvReceiverPhone.setOnClickListener(this);
        mDataBinding.imvDispatchPhone2.setOnClickListener(this);
        mDataBinding.tvDispatchPhone2.setOnClickListener(this);

        mDataBinding.btcollapseDetailLayout.setOnClickListener(this);
        mDataBinding.loadUnloadAddress.btLoadTaskDetailLayout.setOnClickListener(this);
        //显示折叠后的布局
        mDataBinding.collapseTaskLayout.setVisibility(View.VISIBLE);
        //隐藏展开的布局
        mDataBinding.mapTaskDetailLayout.setVisibility(View.GONE);
        mDataBinding.loadUnloadAddress.btLoadTaskDetailLayout.setVisibility(View.VISIBLE);

        // 地图初始化
        mBaiduMap = mDataBinding.bmapView.getMap();
        UiSettings uiSettings = mBaiduMap.getUiSettings();
        uiSettings.setRotateGesturesEnabled(false);//禁止旋转

    }


    /**
     * 创建liveData观察者，用于监听数据变化，从而更新UI
     */
    private void initLiveDataObersve() {
        //监听获取任务详情的数据
        mViewModel.getTaskDetailLiveData().observe(getViewLifecycleOwner(), new Observer<Result<JsonTaskDetailData>>() {
            @Override
            public void onChanged(Result<JsonTaskDetailData> result) {

                result.handler(new OnCallback<JsonTaskDetailData>() {
                    @Override
                    public void onSuccess(JsonTaskDetailData data) {
                        mDataBinding.setTaskDetail(data);
                        //卸货地址可能是空，不为空再显示对应的界面
                        if(!TextUtils.isEmpty(data.unloadingCityName)){
                            mDataBinding.loadUnloadAddress.tvUnLoadDetailAddress.setVisibility(View.VISIBLE);
                        }
                    }
                });
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(BDLocation bdLocation) {
        MyLogCat.i(TAG,"onGetMessage lat="+bdLocation.getLatitude());
        updateMyLocOnMap(bdLocation);
    }
    /**
     * 初始化定位图层，模式为NORMAL
     */
    private void initMyLocationLayer() {
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        // 传入null，则为默认图标
        mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(mCurrentMode, true, null));
        MapStatus.Builder builder1 = new MapStatus.Builder();
        builder1.overlook(0);
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder1.build()));
    }

    @Override
    public int getContentViewId() {
        return R.layout.fragment_map;
    }


    /**
     * 方向传感器
     * @param sensorEvent
     */
    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        double x = sensorEvent.values[SensorManager.DATA_X];
        if (Math.abs(x - lastX) > 1.0) {
            mCurrentDirection = (int) x;
            myLocationData = new MyLocationData.Builder()
                    .accuracy(mCurrentAccracy)// 设置定位数据的精度信息，单位：米
                    .direction(mCurrentDirection)// 此处设置开发者获取到的方向信息，顺时针0-360
                    .latitude(mCurrentLat)
                    .longitude(mCurrentLon)
                    .build();
            mBaiduMap.setMyLocationData(myLocationData);
        }
        lastX = x;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Log.i(TAG, "onAttach");
        mContext = context;
        //实现了Activity中的抽象接口，用以Activity请求到权限结果后，通过接口实例回调通知到Fragment。
        ((MainActivity)mContext).setMyLocationRequestPermission(this);

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btcollapseDetailLayout:
                mDataBinding.mapTaskDetailLayout.setVisibility(View.VISIBLE);
                mDataBinding.collapseTaskLayout.setVisibility(View.GONE);
                break;
            case R.id.btLoadTaskDetailLayout:
                mDataBinding.mapTaskDetailLayout.setVisibility(View.GONE);
                mDataBinding.collapseTaskLayout.setVisibility(View.VISIBLE);
                break;
            case R.id.imgBtMyLoc:
                getMyLocation();
                break;
            case R.id.imgBtTrack:
                Intent i = new Intent(mContext, TrackShowActivity.class);
                i.putExtra("taskId",mCurTaskId);
                startActivity(i);
                break;
            case R.id.tvPublishPhone:
            case R.id.imvPublishPhone:  //出厂电话
                String phone = mDataBinding.loadUnloadAddress.tvPublishPhone.getText().toString();
                callPhone(phone);
                break;

            case R.id.tvReceiverPhone:
            case R.id.imvRecvPhone: //收货电话，客户电话
                String recvPhone = mDataBinding.loadUnloadAddress.tvReceiverPhone.getText().toString();
                callPhone(recvPhone);
                break;

            case R.id.imvDispatchPhone2: //派单人员电话
            case R.id.tvDispatchPhone2:
                String dispathPhone = mDataBinding.tvDispatchPhone2.getText().toString();
                callPhone(dispathPhone);
                break;
        }
    }
    /**
     * 拨打电话
     * @param phone
     */
    private void callPhone(final String phone) {
        if(TextUtils.isEmpty(phone)){
            return;
        }

        //申请多个权限，当所有权限操作完后（批处理），才回调用accept函数，进而才能知道哪个权限被允许了，哪个权限被禁止了。
        final String[] permissionCall = {Manifest.permission.CALL_PHONE};
        RxPermissions permissions = new RxPermissions(getActivity());
        permissions.setLogging(true);
        permissions.requestEach(permissionCall)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        MyLogCat.i(TAG, "checkPermissionRequestEach--:" + "-permission-:" + permission.name + "---------------");
                        if (permission.name.equalsIgnoreCase(Manifest.permission.CALL_PHONE)) {
                            if (permission.granted) {//同意后调用
                                MyLogCat.i(TAG, "checkPermissionRequestEach--:" + "-READ_EXTERNAL_STORAGE-:" + true);
                                Intent intent = new Intent(); // 意图对象：动作 + 数据
                                intent.setAction(Intent.ACTION_CALL); // 设置动作
                                Uri data = Uri.parse("tel:" + phone); // 设置数据
                                intent.setData(data);
                                getActivity().startActivity(intent); // 激活Activity组件
                            } else if (permission.shouldShowRequestPermissionRationale){//禁止，但没有选择“以后不再询问”，以后申请权限，会继续弹出提示
                                MyLogCat.i(TAG, "checkPermissionRequestEach--:" + "-READ_EXTERNAL_STORAGE-shouldShowRequestPermissionRationale:" + false);
                            }else {//禁止，但选择“以后不再询问”，以后申请权限，不会继续弹出提示
                                MyLogCat.i(TAG, "checkPermissionRequestEach--:" + "-READ_EXTERNAL_STORAGE-:" + false);
                                Toast.makeText(getActivity(), R.string.call_failed, Toast.LENGTH_SHORT).show();
                                RxjavaPermissionUtil.getInstance().alertOpenNavPermission(getActivity(),permissionCall);

                            }
                        }
                    }
                });
    }
    /**
     * 获取我的位置
     */
    public void getMyLocation() {
        //先检查权限，权限OK，则开始定位
        String[]permissionGroup = {
                Manifest.permission.ACCESS_FINE_LOCATION,
        };
        RxjavaPermissionUtil.getInstance().checkPermissions((Activity) mContext,permissionGroup);
    }

    public void onGranted() {
        curLocState = STATE_REQUEST_LOC_FOR_CLICK;
        requestMyLocation(false);
    }

    @Override
    public void onDenied(int type) {
        switch (type){
            case 1:
            case 3:
                break;
            case 2:  //勾选了以后不再弹出位置权限提醒
                alertOpenLocationPermission();
                break;
        }
    }
    public void alertOpenLocationPermission()
    {
        AlertDialog.Builder gpsDlgBuilder = new AlertDialog.Builder(mContext);
        gpsDlgBuilder.setTitle(R.string.notifyTitle)
                .setMessage(R.string.location_permission_dlg_tip)
                .setNegativeButton(R.string.cancel,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        })
                .setPositiveButton(R.string.settings,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent();
                                intent.setData(Uri.parse("package:" + mContext.getPackageName()));
                                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                startActivity(intent);
                            }
                        })
                .setCancelable(false);
        AlertDialog gpsDidlog = gpsDlgBuilder.create();
        gpsDidlog.show();

        int colorPrimary = mContext.getResources().getColor(R.color.colorPrimary);
        int colorDescribe = mContext.getResources().getColor(R.color.describe_color);
        gpsDidlog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(colorPrimary);
        gpsDidlog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(colorDescribe);
    }
    /**
     * 请求我的位置
     *
     * @param isShowProgressBar 是否显示进度框
     */
    public void requestMyLocation(boolean isShowProgressBar) {
        if (isShowProgressBar) {
            if (locProgressDialog == null) {
                locProgressDialog = new ProgressDialog(mContext);
            }
            //gxw-locProgressDialog.setCancelable(false);
            locProgressDialog.setMessage("正在确定你的位置,若时间过长请重新尝试……");
            locProgressDialog.show();
        }
        MyApplication.startLocService(); //必须加这一句，因为有时候定位服务关闭了，底下的代码就失效了
        MyApplication.mLocationService.requestLocation();
    }

    /**
     * 定位成功后，改变“我的位置”图标 在 地图上的显示位置
     * @param bdLocation： 我的位置
     */
    public void updateMyLocOnMap(BDLocation bdLocation) {
        if(locProgressDialog != null && locProgressDialog.isShowing()) {
            locProgressDialog.dismiss();
        }
        mCurrentLat = bdLocation.getLatitude();
        mCurrentLon = bdLocation.getLongitude();
        mCurrentAccracy = bdLocation.getRadius();
        myLocationData = new MyLocationData.Builder()
                .accuracy(mCurrentAccracy)// 设置定位数据的精度信息，单位：米
                .direction(mCurrentDirection)// 此处设置开发者获取到的方向信息，顺时针0-360
                .latitude(bdLocation.getLatitude())
                .longitude(bdLocation.getLongitude())
                .build();
        mBaiduMap.setMyLocationData(myLocationData);

        LatLng ll = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.target(ll).zoom(18.0f);
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        MyLogCat.i(TAG,"onHiddenChanged");
        if(!hidden) {  //显示
            EventBus.getDefault().register(this);
            getMyLocation();
            getCurTaskDetail();
        }
        else{
            EventBus.getDefault().unregister(this);
        }
        super.onHiddenChanged(hidden);
    }
    @Override
    public void onStop() {
        MyLogCat.i(TAG,"onStop");
        super.onStop();
    }
    @Override
    public void onStart() {
        MyLogCat.i(TAG,"onStart");
        if(MainActivity.mCurTabIndex == 2) {
            getMyLocation();  //一点开MapFragment就定位
            getCurTaskDetail();
        }
        super.onStart();
    }

    /**
     * 获取当前正在进行的任务（状态为1，2）详情
     */
    public void getCurTaskDetail() {
        mCurTaskId = (!TextUtils.isEmpty(MyApplication.mCurTaskId)) ? MyApplication.mCurTaskId : SPUtils.getString(getActivity(),"curTaskId");

        if(!TextUtils.isEmpty(mCurTaskId)){
            //如果不初始一个数据对象的话,界面显示null,
            JsonTaskDetailData data = new JsonTaskDetailData();
            mDataBinding.setTaskDetail(data);
           // mDataBinding.mapTaskDetailLayout.setVisibility(View.GONE);
            mViewModel.getTaskDetail(mCurTaskId);
        }
        else{
            mDataBinding.imgBtTrack.setVisibility(View.VISIBLE);//Gxw+要恢复
            //mDataBinding.imgBtTrack.setVisibility(View.GONE);//Gxw+要恢复
            mDataBinding.mapTaskDetailLayout.setVisibility(View.GONE);
            mDataBinding.collapseTaskLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void onResume() {
        MyLogCat.i(TAG,"onResume");
        super.onResume();

        mDataBinding.bmapView.onResume();
    }
    @Override
    public void onPause() {
        MyLogCat.i(TAG,"onPause");
        super.onPause();
        // 在activity执行onPause时必须调用mMapView. onPause ()
        mDataBinding.bmapView.onPause();
    }

    @Override
    public void onDestroyView() {
        MyLogCat.i(TAG,"onDestroyView");
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        MyLogCat.i(TAG,"onDestroy");
        super.onDestroy();
        // 取消注册传感器监听
        mSensorManager.unregisterListener(this);
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        // 在activity执行onDestroy时必须调用mMapView.onDestroy()
        mDataBinding.bmapView.onDestroy();

    }
}
